import Config from "@/config"
import { _rootStore } from "@/models/helpers/useStores"
import type { CompletionReq, ServerSentEvent } from "@/services/api/conversations"

import { createSSEClient, SSECallbacks, SSEClient } from "./SSEClient"

const COMPLETION_ENDPOINT = `${Config.BASE_URL}/gpt404/conv/completion`

export type ConversationSSECallbacks = SSECallbacks<ServerSentEvent>

export interface ConversationCompletionOptions extends ConversationSSECallbacks {}

/**
 * 创建会话补全的SSE连接
 * @param payload Completion请求体
 * @param callbacks SSE回调
 * @returns SSEClient 实例，可调用 disconnect()
 */
export const startConversationCompletion = (
  payload: CompletionReq,
  callbacks: ConversationCompletionOptions = {},
): SSEClient => {
  const { accessToken } = _rootStore.userStore

  const client = createSSEClient({
    config: {
      url: COMPLETION_ENDPOINT,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${accessToken}`,
      },
      body: payload,
      timeout: 30000,
    },
    callbacks: {
      ...callbacks,
      onMessage: (data) => {
        let parsed: ServerSentEvent | null = null
        console.log("onmessage", data)
        if (typeof data === "string") {
          try {
            parsed = JSON.parse(data) as ServerSentEvent
          } catch (error) {
            callbacks.onError?.(error as Error)
            return
          }
        } else {
          parsed = data as ServerSentEvent
        }
        const error = parsed.error
        if (error) {
          callbacks.onError?.(error as any)
          return
        }
        callbacks.onMessage?.(parsed)
      },
    },
  })

  client.connect()
  return client
}
